<template>
  <div class="head_top"></div>
  <div class="replenishment_details">
    <div class="device_info">
      <div class="device_name">{{ machineInfoStore.machineInfo?.machineName }}</div>
      <div class="device_xinxi">库存数量：{{ inventory }}</div>
      <div class="device_xinxi">点位：{{ machineInfoStore.machineInfo?.positionName }}</div>
      <div class="device_xinxi">
        状态：{{
          machineInfoStore.machineInfo?.operationStatus === 1
            ? '营业中'
            : machineInfoStore.machineInfo?.operationStatus === 2
              ? '休息中'
              : machineInfoStore.machineInfo?.operationStatus === 3
                ? '故障中'
                : ''
        }}
      </div>
    </div>
    <div class="skip_button">
      <button
        type="button"
        class="_button"
        v-for="(item, index) in skipButtonList"
        :key="item.name"
        @click="activeIndex = index"
        :class="{ active: index === activeIndex }"
      >
        {{ item.name }}
      </button>
    </div>
    <!-- 投放计划表格 -->
    <div v-show="dataList?.length">
      <tableBox
        ref="tableBoxRef"
        :dataList="dataList"
        :activeIndex="activeIndex"
        :machineType="$route.query.machineType"
        @oneClick="oneClick"
        @articleData="articleData"
        @damageData="editComboNum"
      />
      <div class="_submit" v-show="isShow">
        <button type="button" class="button_close" @click="cancel()">取消</button>
        <button type="button" class="button_submit" @click="submit()">提交</button>
      </div>
      <div class="matBox"></div>
    </div>
    <Null_data v-show="!dataList?.length" />
  </div>
  <Tabbar />
  <!-- 弹出层 -->
  <popupBox
    v-model:loopList="loopList"
    :showCenter="showCenter"
    :machineType="$route.query.machineType"
    @popupClose="showCenter = false"
    @editComboNum="editComboNum"
  />
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import tableBox from './components/tableBox.vue'
import popupBox from './components/popupBox.vue'
import { Msg } from '@/utils/tools'
import {
  getRoadInfoApi,
  putRoadInfoApi,
  getDamageDataApi,
  putDamageDataApi,
  getSynchPlanApi,
  postSynchPlanApi,
} from '@/api/machine/machine'
import { useMachineInfoStore } from '@/stores'
import cloneDeep from 'lodash/cloneDeep'
import { showConfirmDialog, showToast } from 'vant'

const $route = useRoute()
const $router = useRouter()
const tableBoxRef = ref(null)
const machineInfoStore = useMachineInfoStore()
const skipButtonList = [{ name: '报损' }, { name: '同步计划' }, { name: '修改库存' }]
const activeIndex = ref(Number($route.query.activeIndex))
const rawDataList = ref([])
const dataList = ref([])
const showCenter = ref(false)
const damageParam = ref([])

let loopList = []
const isShow = ref(true)

const firstTime = ref('')
/**获取设备信息 */
const getMachineInfo = async () => {
  let res = null
  if (activeIndex.value === 0) {
    res = await getDamageDataApi({ machineId: machineInfoStore.machineInfo?.machineId })
    dataList.value = res?.data || []
  } else if (activeIndex.value === 1) {
    res = await getSynchPlanApi({ machineId: machineInfoStore.machineInfo?.machineId })
    dataList.value = res?.data?.list || []
    firstTime.value = res?.data?.firstTime?.slice(11, 16)
  } else if (activeIndex.value === 2) {
    res = await getRoadInfoApi({ machineId: machineInfoStore.machineInfo?.machineId })
    dataList.value = res?.data || []
  }
  rawDataList.value = cloneDeep(dataList.value)
}
// 监听 activeIndex值的变化，初始化数据
watch(
  () => activeIndex.value,
  () => {
    isShow.value = true
    damageParam.value = []
    tableBoxRef.value.closeBoolean()
    getMachineInfo()
  },
)
/**获取子组件点击的单独item */
const oneClick = (item) => {
  if (!item || activeIndex.value === 0) return
  showCenter.value = true
  loopList = [{ ...item }]
}

/**获取子组件点击的单独一行/单独一列 */
const articleData = (list) => {
  if (!list.length) return
  showCenter.value = true
  loopList = cloneDeep(list)
}

/** 随时获取最新的设备库存数量 */
const inventory = computed(() => {
  let sum = 0
  rawDataList.value.forEach((item) => {
    sum += Number(item.comboNum)
  })
  return sum
})

/**点击弹出层 修改 */
const editComboNum = (e) => {
  e.forEach((ev) => {
    dataList.value.forEach((item) => {
      if (ev.roadNumber === item.roadNumber) {
        item.comboNum = ev.comboNum
      }
    })
  })
}
/**点击提交按钮 */
const submit = async () => {
  let res = null
  if (activeIndex.value === 0) {
    const paramAll = dataList.value.map((item) => ({ ...item, comboNum: '0' }))
    res = await putDamageDataApi(damageParam.value.length ? damageParam.value : paramAll)
  } else if (activeIndex.value === 1) {
    if (firstTime.value) {
      showConfirmDialog({
        title: '同步投放计划',
        message: `上次的同步时间为今天${firstTime.value}，确认继续进行同步？`,
        cancelButtonText: '取消',
        cancelButtonColor: '#999999',
        confirmButtonText: '确认',
        confirmButtonColor: '#0DB383',
        messageAlign: 'left'
      })
      .then(async() => {
        res = await postSynchPlanApi(dataList.value)
        if (res.code === 200) {
          console.log('2', 2)
          Msg(
            `${activeIndex.value === 0 ? '报损' : activeIndex.value === 1 ? '同步修改' : '库存修改'}成功`,
          )
        } else {
          return Msg(
            `${activeIndex.value === 0 ? '报损' : activeIndex.value === 1 ? '同步修改' : '库存修改'}失败`,
          )
        }
        isShow.value = false
        getMachineInfo()
      })
      .catch(() => {
        // on cancel
      })
    } else {
      res = await postSynchPlanApi(dataList.value)
    }
  } else if (activeIndex.value === 2) {
    res = await putRoadInfoApi(dataList.value)
  }
  if (activeIndex.value === 1 && firstTime.value) {
    return
  }
  console.log('res', res)
  if (res.code === 200) {
    Msg(
      `${activeIndex.value === 0 ? '报损' : activeIndex.value === 1 ? '同步修改' : '库存修改'}成功`,
    )
  } else {
    return Msg(
      `${activeIndex.value === 0 ? '报损' : activeIndex.value === 1 ? '同步修改' : '库存修改'}失败`,
    )
  }
  isShow.value = false
  getMachineInfo()
}
/**点击取消按钮 */
const cancel = () => {
  $router.go(-1)
}
watch(
  () => showCenter.value,
  (newVal) => {
    newVal === false ? tableBoxRef.value.closeBoolean() : null
  },
)
watch(
  () => dataList.value,
  (newVal) => {
    rawDataList.value.forEach((item) => {
      newVal.forEach((ev) => {
        if (item.roadNumber === ev.roadNumber && item.comboNum !== ev.comboNum) {
          damageParam.value.push(ev)
        }
      })
    })
  },
  { deep: true },
)

getMachineInfo()
</script>

<style lang="scss" scoped>
.head_top {
  height: 44px;
  width: 100vw;
  background-color: #46d9ae;
  position: absolute;
  z-index: 0;
}
.replenishment_details {
  min-height: 636px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .device_info {
    z-index: 9;
    margin-top: 30px;
    width: 347px;
    height: 105px;
    border-radius: 5px;
    background: #fff;
    box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.08);
    padding: 9px 0 0 13px;
    .device_name {
      font-size: 12px;
      color: #000;
    }
    .device_xinxi {
      font-size: 10px;
      color: #999;
      margin-top: 9px;
    }
  }
  .skip_button {
    width: 347px;
    height: 43px;
    display: flex;
    align-items: center;
    ._button {
      height: 20px;
      line-height: 20px;
      padding: 0 15px;
      border-radius: 35px;
      background-color: #e8e8e8;
      color: #000;
      font-size: 12px;
      margin-right: 12px;
    }
    .active {
      background-color: #46d9ae;
      color: #fff;
    }
  }
  .matBox {
    width: 100%;
    height: 100px;
  }
  ._submit {
    margin-top: 14px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 63px;
    .button_close,
    .button_submit {
      width: 91px;
      height: 30px;
      border-radius: 36px;
      font-size: 12px;
    }
    .button_close {
      color: #666;
      border: 1px solid #999;
    }
    .button_submit {
      color: #fff;
      background: #5ed0ae;
    }
  }
}
</style>
